<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="500px"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm">
      <template #type_menu_selected="{ model, field }">
        <TreeSelect
          v-model:value="model[field]"
          style="width: 100%"
          :tree-data="menuList"
          :field-names="{ label: 'name', value: 'code' }"
          :show-search="true"
          treeNodeFilterProp="name"
          :treeDefaultExpandAll="true"
          @change="
            (_, names) => {
              model['name'] = names[0];
            }
          "
        />
      </template>
      <template #type_flow_selected="{ model, field }">
        <TreeSelect
          v-model:value="model[field]"
          style="width: 100%"
          :tree-data="flowList"
          :field-names="{ label: 'name', value: 'code' }"
          :show-search="true"
          treeNodeFilterProp="name"
          :treeDefaultExpandAll="true"
          @change="
            (_, names) => {
              model['name'] = names[0];
            }
          "
        />
      </template>

      <template #moduleCode="{ model, field }">
        <FormItemRest>
          <div class="mb-2 flex gap-2">
            <TreeSelect
              :tree-data="modulesAllList"
              :field-names="{ label: 'name', value: 'code' }"
              treeNodeFilterProp="name"
              show-search
              style="flex: 1"
              v-model:value="model[field]"
              @change="
                (_, names) => {
                  model['name'] = names[0];
                }
              "
            />
            <Checkbox :row="3" v-model:checked="dataRef['isAdd']" v-show="false">增加</Checkbox>
          </div>
        </FormItemRest>
      </template>
      <template #imgUrl="{ model, field }">
        <SelectIconInput v-model:value="model[field]" :options="mobileAppIcons" />
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema, setChildren } from './mobileApplistConfigList.data';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { getModulesAll } from '/@/api/system/system';
  import { getMenuList } from '/@/api/system/system';
  import { getFlowGetDirTreeAll } from '/@/api/flowManage/flowManage';
  import { Checkbox, Form, TreeSelect } from 'ant-design-vue';
  import {
    getAdminCreateMobileAppIcon,
    getAdminEditMobileAppIconPage,
    getAdminUpdateMobileAppIcon,
    getAdminGetMobileAppIcons,
  } from '/@/api/system/system';
  import { useUserStore } from '/@/store/modules/user';
  import { SelectIconInput } from '/@/components/CustomComp';

  export default defineComponent({
    name: 'MobileApplistConfigListDrawer',
    components: {
      BasicDrawer,
      BasicForm,
      Checkbox,
      FormItemRest: Form.ItemRest,
      TreeSelect,
      SelectIconInput,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      const userStore = useUserStore();
      const serverInfo = userStore.getServerInfo;
      let dataRef = ref({});
      const [registerForm, { resetFields, setFieldsValue, validate, updateSchema }] = useForm({
        labelWidth: 150,
        schemas: formSchema,
        showActionButtonGroup: false,
      });

      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        resetFields();
        setDrawerProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        getModulesAllList();
        getMenuListData();
        getFlowGetDirTreeAllData();
        getAdminGetMobileAppIconsData();
        if (unref(isUpdate)) {
          const res = await getAdminEditMobileAppIconPage({ id: data.record.id });
          dataRef.value = {
            ...res,
            type_menu_selected: res.type == 1 ? res.code : '',
            type_flow_selected: res.type == 2 ? res.code : '',
            // type_module_selected: res.type == 3 ? res.code : '',
            moduleCode: res.type == 3 ? res.code : '',
            isAdd: res.isAdd == 1 ? true : false,
            link: res.type == 4 ? res.code : '',
            backgroundColor: res.backgroundColor || '#fff',
            id: data.record.id,
          };
          setFieldsValue({
            ...dataRef.value,
          });
          updateSchema([
            {
              field: 'type',
              componentProps: {
                disabled: true,
              },
            },
          ]);
        } else {
          dataRef.value = {};
          updateSchema([
            {
              field: 'type',
              componentProps: {
                disabled: false,
              },
            },
          ]);
        }
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

      //获取模块
      const modulesAllList = ref([]);
      const getModulesAllList = async () => {
        const data = (await getModulesAll()) || [];
        modulesAllList.value = setChildren(data, false);
      };

      //获取菜单
      const menuList = ref([]);
      const getMenuListData = async () => {
        const { list } = await getMenuList();
        const data = (list && list[0]?.children) ?? [];
        menuList.value = setChildren(data, false);
      };

      //获取流程
      const flowList = ref([]);
      const getFlowGetDirTreeAllData = async () => {
        const data = (await getFlowGetDirTreeAll()) || [];
        flowList.value = setChildren(data);
      };
      //获取图标
      const mobileAppIcons = ref<Recordable[]>([]);
      const getAdminGetMobileAppIconsData = async () => {
        mobileAppIcons.value = [];
        const res = await getAdminGetMobileAppIcons();
        if (res && res.length > 0) {
          res.forEach((item) => {
            mobileAppIcons.value.push({
              label: item.name,
              value: item.path,
            });
          });
        }
      };
      async function handleSubmit() {
        try {
          const values = await validate();
          let formData = Object.assign({}, dataRef.value, values);
          console.log('formData', formData);
          formData.isAdd = formData.isAdd ? 1 : 0;
          setDrawerProps({ confirmLoading: true });
          if (!unref(isUpdate)) {
            await getAdminCreateMobileAppIcon(formData);
          } else {
            formData.type_module_selected = formData.moduleCode;
            await getAdminUpdateMobileAppIcon(formData);
          }

          closeDrawer();
          emit('success');
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }

      return {
        registerDrawer,
        registerForm,
        getTitle,
        handleSubmit,
        dataRef,
        modulesAllList,
        flowList,
        menuList,
        mobileAppIcons,
        serverInfo,
      };
    },
  });
</script>
